package com.ylyq.ylxx.intercepter;

import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

/**
 * @ClassName XssHttpServletRequestWrapper
 * @Description TODO
 * @Author xiaweichao
 * @Date 2020/7/9 10:26
 * @Version 1.0
 */
public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {

    /**
     * @param request
     */
    public XssHttpServletRequestWrapper(HttpServletRequest request) {
        super(request);
    }

    @Override
    public String getParameter(String name) {
        // 过滤getParameter参数 检查是否有特殊字符
        String value = super.getParameter(name);
        if (!StringUtils.isEmpty(value)) {
            // 将中文转换为字符编码格式，将特殊字符变为html源代码保存
//            value = StringEscapeUtils.escapeHtml(value);
            value = StringEscapeUtils.escapeHtml4(value);
        }
        return value;
    }
    /**
     * 对数组参数进行特殊字符过滤
     */
    @Override
    public String[] getParameterValues(String name) {
        String[] values = super.getParameterValues(name);
        if (values == null) {
            return null;
        }
        int count = values.length;
        String[] encodedValues = new String[count];
        for (int i = 0; i < count; i++) {
            encodedValues[i] = StringEscapeUtils.escapeHtml4(values[i]);
        }
        return encodedValues;
    }
    /**
     * 获取attribute,特殊字符过滤
     * 暂时先不用，需要时再放开
     */
    @Override
    public Object getAttribute(String name) {
        Object value = super.getAttribute(name);
        if (value != null && value instanceof String) {
            value = StringEscapeUtils.escapeHtml4((String) value);
        }
        return value;
    }
    /**
     * 对请求头部进行特殊字符过滤
     * 暂时先不用，需要时再放开
     */
//    @Override
//    public String getHeader(String name) {
//        String value = super.getHeader(name);
//        if (value == null) {
//            return null;
//        }
//        return StringEscapeUtils.escapeHtml4(value);
//    }
}
